<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">















  
  
  <link href="/learning/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/learning/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/learning/css/main.css?v=5.1.1" rel="stylesheet" type="text/css">


  <meta name="keywords" content="java,线程池,">








  <link rel="shortcut icon" type="image/x-icon" href="/learning/favicon.ico?v=5.1.1">






<meta name="description" content="java创建线程有两种方式  使用Executors去创建  使用ThreadPoolExecutor的方式去创建   阿里巴巴Java开发文档(六)并发处理中线程池不允许使用Executors去创建，而是通过ThreadPoolExecutor的方式，这样的处理方式让写的同学更加明确线程池的运行规则，规避资源耗尽的风险。 Executors返回的线程池对象的弊端如下 FixedThreadPoo">
<meta name="keywords" content="java,线程池">
<meta property="og:type" content="article">
<meta property="og:title" content="threadFactory的创建">
<meta property="og:url" content="http://yoursite.com/2017/11/05/threadFactory-create/index.html">
<meta property="og:site_name" content="农家男孩的博客">
<meta property="og:description" content="java创建线程有两种方式  使用Executors去创建  使用ThreadPoolExecutor的方式去创建   阿里巴巴Java开发文档(六)并发处理中线程池不允许使用Executors去创建，而是通过ThreadPoolExecutor的方式，这样的处理方式让写的同学更加明确线程池的运行规则，规避资源耗尽的风险。 Executors返回的线程池对象的弊端如下 FixedThreadPoo">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-11-05T02:16:06.476Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="threadFactory的创建">
<meta name="twitter:description" content="java创建线程有两种方式  使用Executors去创建  使用ThreadPoolExecutor的方式去创建   阿里巴巴Java开发文档(六)并发处理中线程池不允许使用Executors去创建，而是通过ThreadPoolExecutor的方式，这样的处理方式让写的同学更加明确线程池的运行规则，规避资源耗尽的风险。 Executors返回的线程池对象的弊端如下 FixedThreadPoo">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/learning/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/11/05/threadFactory-create/">





  <title>threadFactory的创建 | 农家男孩的博客</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/learning/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">农家男孩的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学海无崖</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/learning/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/learning/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/learning/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/learning/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/learning/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/learning/2017/11/05/threadFactory-create/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="wuyoushan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/learning/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="农家男孩的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">threadFactory的创建</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-11-05T10:11:28+08:00">
                2017-11-05
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/learning/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>java创建线程有两种方式</p>
<ol>
<li><p>使用Executors去创建</p>
</li>
<li><p>使用ThreadPoolExecutor的方式去创建</p>
</li>
</ol>
<h3 id="阿里巴巴Java开发文档"><a href="#阿里巴巴Java开发文档" class="headerlink" title="阿里巴巴Java开发文档"></a>阿里巴巴Java开发文档</h3><h4 id="六-并发处理中"><a href="#六-并发处理中" class="headerlink" title="(六)并发处理中"></a>(六)并发处理中</h4><p>线程池不允许使用Executors去创建，而是通过ThreadPoolExecutor的方式，这样的处理方式让写的同学更加明确线程池的运行规则，规避资源耗尽的风险。</p>
<h4 id="Executors返回的线程池对象的弊端如下"><a href="#Executors返回的线程池对象的弊端如下" class="headerlink" title="Executors返回的线程池对象的弊端如下"></a>Executors返回的线程池对象的弊端如下</h4><ul>
<li><p>FixedThreadPool和SingleThreadPool:<br>允许的请求队列长为Integer.MAX_VALUE，可能会堆积大量的请求，从而导致OOM</p>
</li>
<li><p>CachedThreadPool和ScheduledThreadPool:<br>允许的创建线程数量为Integer.MAX_VALUE，可能会创建大量的线程，从而导致OOM</p>
</li>
</ul>
<h3 id="那我们该如何用ThreadPoolExecutor创建线程池呢？"><a href="#那我们该如何用ThreadPoolExecutor创建线程池呢？" class="headerlink" title="那我们该如何用ThreadPoolExecutor创建线程池呢？"></a>那我们该如何用ThreadPoolExecutor创建线程池呢？</h3><h4 id="在此我完全参考了dubbo中创建线程池的方法，代码如下。"><a href="#在此我完全参考了dubbo中创建线程池的方法，代码如下。" class="headerlink" title="在此我完全参考了dubbo中创建线程池的方法，代码如下。"></a>在此我完全参考了dubbo中创建线程池的方法，代码如下。</h4><h4 id="ThreadPool-java代码"><a href="#ThreadPool-java代码" class="headerlink" title="ThreadPool.java代码"></a>ThreadPool.java代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * ThreadPool</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Created by wuyoushan on 2017/10/31.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ThreadPool</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function">Executor <span class="title">getExecutor</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="NamedThreadFactory-java代码"><a href="#NamedThreadFactory-java代码" class="headerlink" title="NamedThreadFactory.java代码"></a>NamedThreadFactory.java代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * InternalThreadFactory</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Created by wuyoushan on 2017/11/1.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NamedThreadFactory</span> <span class="keyword">implements</span> <span class="title">ThreadFactory</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> AtomicInteger POOL_SEQ = <span class="keyword">new</span> AtomicInteger(<span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> AtomicInteger mThreadNum = <span class="keyword">new</span> AtomicInteger(<span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> String mPrefix;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span> mDaemo;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> ThreadGroup mGroup;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">NamedThreadFactory</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(<span class="string">"pool-"</span> + POOL_SEQ.getAndIncrement(), <span class="keyword">false</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">NamedThreadFactory</span><span class="params">(String prefix)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(prefix, <span class="keyword">false</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">NamedThreadFactory</span><span class="params">(String prefix, <span class="keyword">boolean</span> daemo)</span> </span>&#123;</span><br><span class="line">        mPrefix = prefix + <span class="string">"-thread-"</span>;</span><br><span class="line">        mDaemo = daemo;</span><br><span class="line">        SecurityManager s = System.getSecurityManager();</span><br><span class="line">        mGroup = (s == <span class="keyword">null</span>) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Thread <span class="title">newThread</span><span class="params">(Runnable runnable)</span> </span>&#123;</span><br><span class="line">        String name = mPrefix + mThreadNum.getAndIncrement();</span><br><span class="line">        Thread ret = <span class="keyword">new</span> Thread(mGroup, runnable, name, <span class="number">0</span>);</span><br><span class="line">        ret.setDaemon(mDaemo);</span><br><span class="line">        <span class="keyword">return</span> ret;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ThreadGroup <span class="title">getThreadGroup</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> mGroup;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="CachedThreadPool-java代码"><a href="#CachedThreadPool-java代码" class="headerlink" title="CachedThreadPool.java代码"></a>CachedThreadPool.java代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 此线程池可伸缩，线程空闲一分钟后回收，新请求重新创建线程，来源于：&lt;code&gt;Executors.newCachedThreadPool()&lt;/code&gt;</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * Created by wuyoushan on 2017/10/31.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CachedThreadPool</span> <span class="keyword">implements</span> <span class="title">ThreadPool</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Executor <span class="title">getExecutor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        String name = <span class="string">"Dubbo"</span>;</span><br><span class="line">        <span class="keyword">int</span> cores = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> threads = Integer.MAX_VALUE;</span><br><span class="line">        <span class="keyword">int</span> queues = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> alive = <span class="number">60</span> * <span class="number">1000</span>;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ThreadPoolExecutor(cores, threads, alive, TimeUnit.MILLISECONDS,</span><br><span class="line">                queues == <span class="number">0</span> ? <span class="keyword">new</span> SynchronousQueue&lt;Runnable&gt;() :</span><br><span class="line">                        (queues &lt; <span class="number">0</span> ? <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;()</span><br><span class="line">                                : <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;(queues)),</span><br><span class="line">                <span class="keyword">new</span> NamedThreadFactory(name, <span class="keyword">true</span>), <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="FixedThreadPool-java代码"><a href="#FixedThreadPool-java代码" class="headerlink" title="FixedThreadPool.java代码"></a>FixedThreadPool.java代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 此线程池启动时即创建固定大小的线程数，不做任何伸缩，来源于：&lt;code&gt;Executors.newFixedThreadPool()&lt;/code&gt;</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Created by wuyoushan on 2017/10/31.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FixedThreadPool</span> <span class="keyword">implements</span> <span class="title">ThreadPool</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Executor <span class="title">getExecutor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        String name = <span class="string">"Dubbo"</span>;</span><br><span class="line">        <span class="keyword">int</span> threads = <span class="number">200</span>;</span><br><span class="line">        <span class="keyword">int</span> queues = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ThreadPoolExecutor(threads,threads,<span class="number">0</span>, TimeUnit.MILLISECONDS,</span><br><span class="line">                queues == <span class="number">0</span> ? <span class="keyword">new</span> SynchronousQueue&lt;Runnable&gt;() :</span><br><span class="line">                        (queues &lt; <span class="number">0</span> ? <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;()</span><br><span class="line">                                : <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;(queues)),</span><br><span class="line">                <span class="keyword">new</span> NamedThreadFactory(name, <span class="keyword">true</span>), <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="LimitedThreadPool-java代码"><a href="#LimitedThreadPool-java代码" class="headerlink" title="LimitedThreadPool.java代码"></a>LimitedThreadPool.java代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 此线程池一直增长，直到上限，增长后不收缩。</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Created by wuyoushan on 2017/10/31.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LimitedThreadPool</span> <span class="keyword">implements</span> <span class="title">ThreadPool</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Executor <span class="title">getExecutor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        String name = <span class="string">"Dubbo"</span>;</span><br><span class="line">        <span class="keyword">int</span> cores = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> threads = <span class="number">200</span>;</span><br><span class="line">        <span class="keyword">int</span> queues = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ThreadPoolExecutor(cores,threads,Long.MAX_VALUE, TimeUnit.MILLISECONDS,</span><br><span class="line">                queues == <span class="number">0</span> ? <span class="keyword">new</span> SynchronousQueue&lt;Runnable&gt;() :</span><br><span class="line">                        (queues &lt; <span class="number">0</span> ? <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;()</span><br><span class="line">                                : <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;(queues)),</span><br><span class="line">                <span class="keyword">new</span> NamedThreadFactory(name, <span class="keyword">true</span>), <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="注意"><a href="#注意" class="headerlink" title="注意:"></a>注意:</h3><p>上面的线程池的创建和JDK中Executors基于Executors和ThreadPoolExecutor是有所差异的。</p>
<ol>
<li><p>dubbo中线程池创建的线程为守护进程，而使用Executors和ThreadPoolExecutor默认线程工厂创建的线程池为非守护线程。</p>
</li>
<li><p>dubbo中根据参数使用的阻塞队列，以及定义队列的长度都是不一样的。</p>
</li>
</ol>
<h4 id="上面代码完全参考自dubbo项目源码"><a href="#上面代码完全参考自dubbo项目源码" class="headerlink" title="上面代码完全参考自dubbo项目源码"></a>上面代码完全参考自dubbo项目源码</h4><p>git地址 <a href="https://github.com/alibaba/dubbo" target="_blank" rel="noopener">https://github.com/alibaba/dubbo</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/learning/tags/java/" rel="tag"># java</a>
          
            <a href="/learning/tags/线程池/" rel="tag"># 线程池</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/learning/2017/10/24/thread-future-callable/" rel="next" title="java多线程 Callable和Future的使用">
                <i class="fa fa-chevron-left"></i> java多线程 Callable和Future的使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/learning/2018/03/01/mybatis-cross-database/" rel="prev" title="spring整合mybatis实现跨库(实现主从查询)">
                spring整合mybatis实现跨库(实现主从查询) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image" src="/learning/images/avatar.gif" alt="wuyoushan">
          <p class="site-author-name" itemprop="name">wuyoushan</p>
           
              <p class="site-description motion-element" itemprop="description">W3C菜鸟</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/learning/archives/">
                <span class="site-state-item-count">61</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/learning/categories/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/learning/tags/index.html">
                <span class="site-state-item-count">8</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="http://git.oschina.net/wuyoushan" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="翟永超的博客" target="_blank">翟永超的博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://itmuch.com/" title="周立的博客" target="_blank">周立的博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.bysocket.com/" title="泥瓦匠的博客" target="_blank">泥瓦匠的博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.720ui.com/" title="梁桂钊的博客" target="_blank">梁桂钊的博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://kailing.pub/" title="KL博客" target="_blank">KL博客</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#阿里巴巴Java开发文档"><span class="nav-number">1.</span> <span class="nav-text">阿里巴巴Java开发文档</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#六-并发处理中"><span class="nav-number">1.1.</span> <span class="nav-text">(六)并发处理中</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Executors返回的线程池对象的弊端如下"><span class="nav-number">1.2.</span> <span class="nav-text">Executors返回的线程池对象的弊端如下</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#那我们该如何用ThreadPoolExecutor创建线程池呢？"><span class="nav-number">2.</span> <span class="nav-text">那我们该如何用ThreadPoolExecutor创建线程池呢？</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#在此我完全参考了dubbo中创建线程池的方法，代码如下。"><span class="nav-number">2.1.</span> <span class="nav-text">在此我完全参考了dubbo中创建线程池的方法，代码如下。</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ThreadPool-java代码"><span class="nav-number">2.2.</span> <span class="nav-text">ThreadPool.java代码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#NamedThreadFactory-java代码"><span class="nav-number">2.3.</span> <span class="nav-text">NamedThreadFactory.java代码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#CachedThreadPool-java代码"><span class="nav-number">2.4.</span> <span class="nav-text">CachedThreadPool.java代码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#FixedThreadPool-java代码"><span class="nav-number">2.5.</span> <span class="nav-text">FixedThreadPool.java代码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#LimitedThreadPool-java代码"><span class="nav-number">2.6.</span> <span class="nav-text">LimitedThreadPool.java代码</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注意"><span class="nav-number">3.</span> <span class="nav-text">注意:</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#上面代码完全参考自dubbo项目源码"><span class="nav-number">3.1.</span> <span class="nav-text">上面代码完全参考自dubbo项目源码</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">wuyoushan</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/learning/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/learning/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/learning/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/learning/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/learning/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/learning/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/learning/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/learning/js/src/motion.js?v=5.1.1"></script>



  
  


  <script type="text/javascript" src="/learning/js/src/affix.js?v=5.1.1"></script>

  <script type="text/javascript" src="/learning/js/src/schemes/pisces.js?v=5.1.1"></script>



  
  <script type="text/javascript" src="/learning/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/learning/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/learning/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/learning/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

</body>
</html>
